<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in">
      <div class="cornerComment-in-title">
        <span>添加/编辑楼层平面分区</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody">
        <el-form label-width="140px" ref="editForm">
          <el-form-item label="分区类型：" prop="name">
            <el-select v-model="pointType" placeholder="请选择坐标类型" @change="selectFn" size="small">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文字名称：" v-if="pointType==1">
            <el-input v-model="pointName" auto-complete="off" placeholder="文字名称" size="small"></el-input>
          </el-form-item>
          <!--          <el-form-item label="设备名称：" v-if="pointType==2">-->
          <!--            <el-input v-model="deviceName" auto-complete="off" placeholder="设备名称"></el-input>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="设备IP：" v-if="pointType==2">-->
          <!--            <el-input v-model="deviceIP" auto-complete="off" placeholder="设备IP"></el-input>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="设备账号：" v-if="pointType==2">-->
          <!--            <el-input v-model="username" auto-complete="off" placeholder="设备账号"></el-input>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="设备密码：" v-if="pointType==2">-->
          <!--            <el-input v-model="password" auto-complete="off" placeholder="设备密码"></el-input>-->
          <!--          </el-form-item>-->
          <el-form-item label="硬盘录像机：" v-if="pointType==2">
            <el-select v-model="recorderId" placeholder="请选择硬盘录像机" size="small" @change="selectBrandFn">
              <el-option v-for="item in videoRecorder" :key="item.id" :label="item.pointname" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="摄像头：" v-if="pointType==2">
            <el-select v-model="cameraId" placeholder="请选择摄像头" size="small">
              <el-option v-for="item in cameraList" :key="item.id" :label="item.pointername" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="位置：" v-if="pointType==2">
            <component v-bind:is="item.propertyType" :property.sync="item" v-for="(item, index) in getPower" :key="index" @updateVal="updateVal"></component>
          </el-form-item>
          <el-form-item label="巡更设备：" v-if="pointType==4">
            <el-button @click="changeDev">选择设备</el-button>
            {{ ruleForm.deviceId ? `【${ruleForm.deviceId}】` : "" }}
          </el-form-item>
<!--          <el-form-item label="选择卡号：" v-if="pointType==4">-->
<!--            <el-select v-model="ruleForm.cardNo" placeholder="请选择卡号" filterable>-->
<!--              <el-option v-for="(item, index) in cardUser" :key="index" :label="item.name" :value="item.cardNumber"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="巡更时间：" v-if="pointType==4">-->
<!--            <el-button @click="changeKeeptime">选择巡更时间</el-button>-->
<!--            {{ ruleForm.keepTimes ? `【${ruleForm.keepTimes}】` : "" }}-->
<!--          </el-form-item>-->

          <el-form-item label="选择对应区角：" prop="warming" v-if="pointType==3">
            <el-button @click.native="chooseCornerFn" size="small">选择区角</el-button>
            {{ dynamicTagsArray ? dynamicTagsArray.name : '' }}
          </el-form-item>
          <el-form-item label="选择对应地图区域：" prop="warming">
            <el-button @click.native="choosePointFn" size="small">选择地图区域</el-button>
            {{ pointMap ? `${pointMap[0]},${pointMap[1]}` : '' }}
          </el-form-item>
        </el-form>
      </div>
      <div class="cornerComment-in-footer">
        <el-button @click.native="closePOpup" size="small">取消</el-button>
        <el-button @click="submitBook" size="small" type="primary">确定并保存</el-button>
      </div>
    </div>
    <pointMap :visible.sync="pointVisible" :pointInfo="{type: pointType,name: pointType==1?pointName:'',point:pointMap}" @getPoint="getPoint" :mapPic="mapPic"></pointMap>
    <cornerListSingle :visible.sync="cornerVisible" @studentFn="studentFn" :dynamicTagsArray="dynamicTagsArray"></cornerListSingle>

    <!-- 查询设备列表 -->
    <el-dialog title="设备列表" :visible.sync="dialogVis" width="50%" :append-to-body="true">
      <div style="overflow: hidden">
        <el-table :data="arryList" ref="deviceTable" :stripe="tableStripe" :border="tableBorder" tooltip-effect="dark" header-cell-class-name="table-text-c" cell-class-name="table-text-c">
          <el-table-column align="center" label="位置" prop="position" />
          <el-table-column align="center" label="状态" prop="status">
            <template slot-scope="scope">{{ scope.row.status == "online" ? "在线" : "离线" }}</template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="primary" @click="toggleSelection('device',scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--工具条 分页-->
<!--        <el-col :span="24" class="toolbar">-->
<!--          <el-pagination background :page-size="page.pagesize" :current-page="page.pageindex" layout="total, prev, pager, next" :total="page.total" @current-change="handleSizeChange"></el-pagination>-->
<!--        </el-col>-->
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="toggleSelection('device')">选择</el-button>
        <el-button @click="toggleClear('device')">取消选择</el-button>
      </span>-->
    </el-dialog>

    <!-- 巡更时间点列表 -->
    <el-dialog title="巡更时间列表" :visible.sync="dialogTime" width="50%" :append-to-body="true">
      <div class="rightBodyContent-in">
        <el-table :data="timeList" ref="keeptimeTable" :stripe="tableStripe" :border="tableBorder" tooltip-effect="dark" header-cell-class-name="table-text-c" cell-class-name="table-text-c">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column align="center" prop="id" label="id" />
          <el-table-column align="center" label="时间点" prop="times" />
        </el-table>
        <!--工具条 分页-->
        <el-col :span="24" class="toolbar">
          <el-pagination background :page-size="page.pagesize" :current-page="page.pageindex" layout="total, prev, pager, next" :total="page.total" @current-change="handleSizeChange"></el-pagination>
        </el-col>
      </div>
      <span style="margin-bottom: 20px" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="toggleSelection('keeptime')">选择</el-button>
        <el-button @click="toggleClear('keeptime')">取消选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pointMap from "./pointMap";
import { pagination } from "@/utils/util.js";
// import cornerListSingle from "@/components/modleTemplate/cornerListSingle";
import { mapGetters } from "vuex";
import { recorderIndex, recorderCamera } from "@/api/admin/cameraVideo";
import { devicelist, porstuser, qualityAdd, recdocList } from "@/api/xungen.js";
export default {
  props: ["visible", "pointId", "floorId", "mapPic"], // commoent 学生点评 collection 学生采集
  components: {
    pointMap,
    // cornerListSingle
  },
  computed: {
    ...mapGetters(["configData"]),
  },
  data() {
    return {
      cornerVisible: false,
      dialogVisible: false,
      dialogTime: false,
      dialogVis: false,
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      timeList: [],
      arryList: [],
      cardUser: [],
      ruleForm: {
        cardNo: "",
        deviceId: '',
        keepTimes: '',
      },
      options: [
        {
          value: "1",
          label: "名称",
        },
        {
          value: "2",
          label: "监控",
        },
        {
          value: "3",
          label: "区角",
        },
        {
          value: "4",
          label: "巡更",
        },
      ],
      // brandList: [{
      //   value: 1,
      //   label: '大华',
      //   port: 2000
      // }, {
      //   value: 2,
      //   label: '其他',
      //   port: 3000
      // }],
      brandId: "",
      pointVisible: false,
      pointType: "",
      pointName: "",
      pointMap: "", // 坐标
      deviceIP: "",
      deviceName: "",
      corner: "",
      username: "",
      password: "",
      dynamicTagsArray: null,
      recorderId: "",
      videoRecorder: [],
      cameraList: [],
      cameraId: "",
      editForm: {
        class_id: "", // 班级id
        section_id: "", // 年段id
      }, // 编辑界面数据
      getPower: {
        section_id: {
          name: "section_id", // key名称
          default: "", // 默认值
          propertyType: "Select", // 组件名称
          placeholder: "区域", // 默认值
          valueText: "", // 值
          leve: 2,
          api: this.api.user_sectionindex, // 下拉框的请求接口
          keyName: "section_name", // 调用的字段
          child: [
            {
              name: "class_id",
              default: "",
              propertyType: "",
              placeholder: "位置",
              valueText: "",
              api: this.api.user_classesindex,
              keyName: "class_name",
            },
          ],
        },
      },
      rulrName: "",
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total,
      },
    };
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible;
      if (this.visible) {
        if (this.pointId) {
          this.getDetail();
        }
      } else {
        this.pointType = "";
        this.pointName = "";
        this.pointMap = "";
        this.deviceIP = "";
        this.deviceName = "";
        this.brandId = "";
        this.username = "";
        this.password = "";
        this.recorderId = "";
        this.videoRecorder = [];
        this.cameraList = [];
        this.cameraId = "";
        // this.ruleForm = {
        //   cardNo: "",
        //   deviceId: [],
        //   keepTimes: [],
        // };
        let newGetPower = this.getJson(this.getPower);
        newGetPower["section_id"].valueText = "";
        newGetPower["section_id"].child[0].valueText = "";
        this.getPower = newGetPower;
      }
    },
  },
  created() {},
  methods: {
    submitBook() {
      // 判断新增 编辑
      if (!this.pointType) {
        this.$message.error("选择坐标类型");
        return;
      }
      if (Number(this.pointType) === 1 && !this.pointName) {
        this.$message.error("填写文字名称");
        return;
      }
      if (Number(this.pointType) === 2 && !this.recorderId) {
        this.$message.error("选择录像机");
        return;
      }
      if (Number(this.pointType) === 2 && !this.cameraId) {
        this.$message.error("选择摄像头");
        return;
      }
      // if (Number(this.pointType) === 4 && !this.ruleForm.cardNo) {
      //   this.$message.error("选择卡号");
      //   return;
      // }
      if (Number(this.pointType) === 4 && !this.ruleForm.deviceId) {
        this.$message.error("选择设备");
        return;
      }
      // if (Number(this.pointType) === 4 && !this.ruleForm.keepTimes) {
      //   this.$message.error("选择巡更时间点");
      //   return;
      // }
      if (
        Number(this.pointType) === 2 &&
        (!this.editForm.section_id || !this.editForm.section_id)
      ) {
        this.$message.error("选择摄像头位置");
        return;
      }
      if (!this.pointMap) {
        this.$message.error("选择坐标点");
        return;
      }
      let data_ = {
        map_id: this.floorId, // 楼层
        type: this.pointType, // 类型  文字，摄像头， 区角
        data: {
          name: this.pointName, // 文字名称，设备名称
          point: this.pointMap,
        },
      };
      if (this.pointId) {
        data_.id = this.pointId; // 编辑坐标点
      }
      let recorder_data = "";
      let camera_data = "";
      let data_line = {
        name: this.pointName, // 文字名称，设备名称
        point: this.pointMap,
      };
      if (Number(this.pointType) === 2) {
        for (let item of this.videoRecorder) {
          if (item.id === this.recorderId) {
            data_line.recorder_data = item;
          }
        }
        for (let item of this.cameraList) {
          if (item.id === this.cameraId) {
            data_line.camera_data = item;
          }
        }
        data_line.class_data = this.editForm;
      }
      if (Number(this.pointType) === 3) {
        data_line.corner = {
          corner: this.dynamicTagsArray ? this.dynamicTagsArray.id : 0,
          name: this.dynamicTagsArray ? this.dynamicTagsArray.name : 0,
        };
      }
      if (Number(this.pointType) === 4) {
        data_line.ruleform = this.ruleForm;
        data_line.name = this.rulrName;
      }
      data_.data = JSON.stringify(data_line);
      console.log(data_line, "data_line");
      // 点位坐标分为，文字，摄像头， 区角
      // 基础字段 类型 区域坐标 名称
      // 摄像头需要 录像机 ip 摄像头 ip id
      this.$post(
        this.pointId ? this.api.floor.pointEdit : this.api.floor.pointAdd,
        data_
      )
        .then((response) => {
          if (!response.code) {
            this.$message.success(response.msg);
            this.$emit("InitFn");
            this.closePOpup();
          } else {
            this.$message.error(response.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async InitFn() {
      let data = await this.$fetch(this.api.floor.edit, { id: this.floorId });
      console.log("data物料信息:", data);
      if (!data.code) {
        this.editForm.name = data.vo.name;
        this.editForm.map = data.vo.map;
      } else {
      }
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit("update:visible", false);
    },
    getPoint(option) {
      console.log("收到的坐标", option);
      this.pointMap = this.getJson(option);
    },
    choosePointFn() {
      if (!this.pointType) {
        this.$message.error("选择坐标类型");
      } else {
        if (Number(this.pointType) === 1 && !this.pointName) {
          this.$message.error("填写文字名称");
          return;
        }
        this.pointVisible = true;
      }
    },
    selectFn() {
      this.pointName = "";
      this.pointMap = "";
      this.deviceIP = "";
      this.deviceName = "";
      console.log(this.pointType);
      if (Number(this.pointType) !== 3) {
        this.dynamicTagsArray = null;
      }
      if (Number(this.pointType) === 4) {
        this.handleUser();
      }
      // 选择摄像头
      if (Number(this.pointType) === 2 && !this.configData.video_url) {
        this.$confirm(
          "未获取硬盘录像机接口，请于【设置】=》【视频接口地址】进行设置！（例：http://xxx.xxx.xxx）",
          "提示",
          {
            confirmButtonText: "确定",
            showCancelButton: false,
            type: "warning",
          }
        )
          .then(() => {})
          .catch(() => {});
      }
      if (Number(this.pointType) === 2 && this.configData.video_url) {
        this.getRecorderFn();
      }
    },
    getRecorderFn(option) {
      let port_ = this.configData.video_port
        ? ":" + this.configData.video_port
        : "";
      recorderIndex(`${this.configData.video_url}${port_}`, {
        pageNum: 1,
        pageSize: 1000,
      }).then((res) => {
        console.log("获取接口的硬盘录像机:", res);
        this.videoRecorder = res.rows;
        if (option === "edit") {
          this.selectBrandFn();
        }
      });
    },
    // 选择摄像头
    selectBrandFn() {
      let port_ = this.configData.video_port
        ? ":" + this.configData.video_port
        : "";
      console.log(this.configData.video_url, port_, " this.configData");
      recorderCamera(`${this.configData.video_url}${port_}`, {
        recorderId: this.recorderId,
        pageNum: 1,
        pageSize: 1000,
      }).then((res) => {
        console.log("摄像头:", res);
        this.cameraList = res.rows;
      });
    },
    getDetail() {
      this.$fetch(this.api.floor.pointEdit, {
        id: this.pointId,
      }).then((response) => {
        this.pointType = response.vo.type.toString();
        let dataOption = JSON.parse(response.vo.data);
        this.pointName = Number(response.vo.type) === 1 ? dataOption.name : "";
        this.recorderId =
          Number(response.vo.type) === 2 ? dataOption.recorder_data.id : "";
        this.cameraId =
          Number(response.vo.type) === 2 ? dataOption.camera_data.id : "";
        this.pointMap = dataOption.point;
        if (Number(response.vo.type) === 4) {
          this.ruleForm = dataOption.ruleform;
        }
        if (dataOption.class_data) {
          this.editForm = JSON.parse(JSON.stringify(dataOption.class_data));
          let newGetPower = this.getJson(this.getPower);
          newGetPower["section_id"].valueText =
            dataOption.class_data["section_id"];
          newGetPower["section_id"].child[0].valueText =
            dataOption.class_data["class_id"];
          this.getPower = newGetPower;
        }
        if (Number(response.vo.type) === 3) {
          this.dynamicTagsArray = this.getJson(dataOption.corner);
        }
        // 获取录像机，摄像头信息
        this.getRecorderFn("edit");
      });
    },
    // 收到区角数据
    studentFn(option) {
      console.log("收到数据内容：", option);
      this.dynamicTagsArray = this.getJson(option);
      this.cornerVisible = false;
    },
    chooseCornerFn() {
      this.cornerVisible = true;
    },
    getJson(item) {
      return JSON.parse(JSON.stringify(item));
    },
    // 获取配置你
    getUrlDoc() {
      let n = this;
      this.getSetting().then((res) => {
        console.log("系统信息内容：", res);
        if (
          !res.vo.url &&
          (res.vo.url.indexOf("http://") || res.vo.url.indexOf("https://"))
        ) {
          this.$confirm(
            "未获取学校链接，请请联系管理员正确填写网址！（例：http://xxx.xxx.xxx）",
            "提示",
            {
              confirmButtonText: "确定",
              showCancelButton: false,
              type: "warning",
            }
          )
            .then(() => {})
            .catch(() => {});
          return;
        }
        this.url_ = res.vo.url;
        this.insertSetFn();
        // this.$nextTick(() => {
        //   n.qrcode(res.vo.url)
        // })
      });
    },
    // 更新值
    updateVal(option) {
      // console.log('变更数据收到的数据内容：', option)
      if (option.input) {
        this.editForm[option["input"].name] = option["input"].valueText;
      } else if (option.select) {
        for (let i in option.select) {
          if (option.select[i].name) {
            this.editForm[option.select[i].name] = option.select[i].valueText;
          } else {
            this.editForm[option.select[i - 1].name] = option.select[i]
              .valueText
              ? option.select[i].valueText
              : option.select[i - 1].valueText;
          }
        }
      }
    },

    // 选择卡号
    handleUser() {
      let port_ = this.configData.keep_port
        ? ":" + this.configData.keep_port
        : "";
      porstuser(`${this.configData.keep_url}${port_}`, {}).then((res) => {
        console.log(res, "res");
        this.cardUser = res.rows;
      });
    },
    // 选择设备列表
    changeDev() {
      let port_ = this.configData.keep_port
        ? ":" + this.configData.keep_port
        : "";
      devicelist(`${this.configData.keep_url}${port_}`, {page: 1,pageSize : 100}).then((res) => {
        this.arryList = res.rows;
        // this.page.total = res.total;
      });
      // 选择卡号
      this.dialogVis = true;
    },

    // 选择巡更时间列表
    changeKeeptime() {
      let port_ = this.configData.keep_port
        ? ":" + this.configData.keep_port
        : "";
      qualityAdd(`${this.configData.keep_url}${port_}`).then((res) => {
        this.timeList = res.rows;
        this.page.total = res.total;
      });
      this.dialogTime = true;
    },
    toggleSelection(data, index) {
      if (data == "device") {
        this.ruleForm.deviceId = [index.id];
        this.rulrName = index.position;
        this.dialogVis = false;
      } else if (data == "keeptime") {
        this.ruleForm.keepTimes = this.$refs.keeptimeTable.selection.map(
          (v) => v.times
        );
        this.dialogTime = false;
      }
    },

    toggleClear(data) {
      if (data == "device") {
        this.$refs.deviceTable.clearSelection();
        this.dialogVis = false;
      } else if (data == "keeptime") {
        this.$refs.keeptimeTable.clearSelection();
        this.dialogTime = false;
      }
    },
    handleSizeChange(val) {
      this.page.pageindex = val;
    },
  },
  mounted() {},
};
</script>
<style scoped>
#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 50%;
  height: 45%;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

.close-Btn-line {
  cursor: pointer;
}
</style>


